import { app, BrowserWindow, ipcMain } from 'electron'
import { join } from 'path'
import { configStore } from './storage/ConfigStore'

const isDev = process.argv.includes('--dev')

function createWindow(): void {
  const mainWindow = new BrowserWindow({
    width: 1200,
    height: 800,
    minWidth: 800,
    minHeight: 600,
    title: '融媒智创工坊',
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
      preload: join(__dirname, '../preload/preload.js'),
      webSecurity: true,  // 保持Web安全但允许外部请求
      allowRunningInsecureContent: false
    },
    titleBarStyle: process.platform === 'darwin' ? 'hiddenInset' : 'default',
    titleBarOverlay: process.platform === 'win32' ? {
      color: '#ffffff',
      symbolColor: '#000000'
    } : false,
    trafficLightPosition: process.platform === 'darwin' ? {
      x: 16,
      y: 16
    } : undefined,
    show: false
  })

  // 窗口准备好后再显示，避免视觉闪烁
  mainWindow.once('ready-to-show', () => {
    mainWindow.show()
  })

  if (isDev) {
    mainWindow.loadURL('http://localhost:5175')
    mainWindow.webContents.openDevTools()
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }
}

app.whenReady().then(() => {
  console.log('[Main] 使用IndexedDB存储(渲染进程)')
  console.log('[Main] 使用JSON文件配置存储(主进程)')

  // 配置session允许外部API请求
  const { session } = require('electron')
  const ses = session.defaultSession

  // 设置CSP允许外部API调用
  ses.webRequest.onHeadersReceived((details: any, callback: any) => {
    callback({
      responseHeaders: {
        ...details.responseHeaders,
        'Content-Security-Policy': [
          "default-src 'self' 'unsafe-inline' 'unsafe-eval' data: https://api.openai.com https://api.siliconflow.cn https://*;"
        ]
      }
    })
  })

  createWindow()

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit()
})

// IPC 处理程序示例
ipcMain.handle('get-app-version', () => {
  return app.getVersion()
})

ipcMain.handle('get-app-name', () => {
  return app.getName()
})

// 网络请求处理器
ipcMain.handle('fetch', async (_event, url: string, options: any) => {
  const { net } = require('electron')

  try {
    console.log('[Main] 发起网络请求:', url)

    const request = net.request({
      method: options.method || 'GET',
      url: url
    })

    // 设置请求头
    if (options.headers) {
      Object.entries(options.headers).forEach(([key, value]) => {
        request.setHeader(key, value as string)
      })
    }

    return new Promise((resolve, reject) => {
      let responseData = ''

      request.on('response', (response: any) => {
        console.log('[Main] 收到响应:', response.statusCode)

        response.on('data', (chunk: any) => {
          responseData += chunk.toString()
        })

        response.on('end', () => {
          try {
            const result = {
              ok: response.statusCode >= 200 && response.statusCode < 300,
              status: response.statusCode,
              statusText: response.statusMessage,
              data: responseData
            }
            console.log('[Main] 请求完成:', result.ok)
            resolve(result)
          } catch (error) {
            reject(error)
          }
        })

        response.on('error', (error: any) => {
          console.error('[Main] 响应错误:', error)
          reject(error)
        })
      })

      request.on('error', (error: any) => {
        console.error('[Main] 请求错误:', error)
        reject(error)
      })

      // 发送请求体
      if (options.body) {
        request.write(options.body)
      }

      request.end()
    })
  } catch (error) {
    console.error('[Main] Fetch异常:', error)
    throw error
  }
})

// ========== 存储服务 IPC 处理器 ==========
// 注意: 文档存储已迁移到渲染进程的IndexedDB
// 主进程不再处理文档存储,仅保留IPC接口以兼容旧代码
console.log('[Main] 文档存储使用IndexedDB(渲染进程直接访问)')

// ========== 配置存储 IPC 处理器 ==========

// 获取所有配置
ipcMain.handle('config:get-all', () => {
  return configStore.getAll()
})

// 获取特定配置
ipcMain.handle('config:get', (_event, key: string) => {
  return configStore.get(key as any)
})

// 设置配置
ipcMain.handle('config:set', (_event, key: string, value: any) => {
  configStore.set(key as any, value)
  return true
})

// 获取AI配置
ipcMain.handle('config:get-ai', () => {
  return configStore.getAIConfig()
})

// 设置AI配置
ipcMain.handle('config:set-ai', (_event, config: any) => {
  configStore.setAIConfig(config)
  return true
})

// 获取编辑器配置
ipcMain.handle('config:get-editor', () => {
  return configStore.getEditorConfig()
})

// 设置编辑器配置
ipcMain.handle('config:set-editor', (_event, config: any) => {
  configStore.setEditorConfig(config)
  return true
})

// 添加最近文档
ipcMain.handle('config:add-recent-document', (_event, documentId: string) => {
  configStore.addRecentDocument(documentId)
  return true
})

// 获取最近文档
ipcMain.handle('config:get-recent-documents', () => {
  return configStore.getRecentDocuments()
})

// 重置配置
ipcMain.handle('config:reset', () => {
  configStore.reset()
  return true
})

console.log('[Main] ✅ 配置存储IPC处理器已注册')
console.log('[Main] 📁 配置文件路径:', configStore.getConfigPath())